// @ts-ignore
import vue from "@vitejs/plugin-vue";
import * as path from "path";
import { defineConfig } from "vite";

export default defineConfig(
  ({ mode, command }: { mode: string; command: string }) => {
    return {
      base: "/",
      plugins: [vue()],
      resolve: {
        alias: {
          "~": path.resolve(__dirname, "./"),
          "@": path.resolve(__dirname, "./src"),
        },
        extensions: [".mjs", ".js", ".ts", ".jsx", ".tsx", ".json", ".vue"],
      },
      // 打包配置
      build: {
        sourcemap: command === "build" ? false : "inline",
        outDir: process.env.VITE_OUT_DIR || "dist",
        assetsDir: "assets",
        chunkSizeWarningLimit: 2000,
        rollupOptions: {
          // 按模块分割chunk
          manualChunks: {
            vue: ["vue", "vue-router", "pinia"],
            "element-plus": ["element-plus", "@element-plus/icons-vue"],
            echarts: ["echarts"],
          },
          // 静态资源命名（带hash值，避免缓存问题）
          assetFileNames: {
            css: "static/css/[name].[contenthash].css",
            js: "static/js/[name].[contenthash].js",
            images: "static/img/[name].[contenthash].[ext]",
            svg: "static/svg/[name].[contenthash].[ext]",
            fonts: "static/fonts/[name].[contenthash].[ext]",
          },
          output: {
            chunkFileNames: "static/js/[name]-[hash].js",
            entryFileNames: "static/js/[name]-[hash].js",
            assetFileNames: "static/[ext]/[name]-[hash].[ext]",
          },
        },
      },
      server: {
        host: true,
        port: 6210,
        strictPort: true,
        open: true,
        proxy: {
          "/HeBeiHaiYangDataAnalysis": {
            target: "http://lc.guo.lol:28080",
            changeOrigin: true,
            rewrite: (p) => p.replace(/^\/dev-api/, ""),
          },
        },
      },
      css: {
        preprocessorOptions: {
          scss: {
            charset: false, // 解决Scss编译的编码问题
          },
        },
        devSourcemap: mode === "development", // 开发环境生成CSS sourcemap
        modules: {
          // CSS Modules配置（避免样式冲突，如使用<style module>）
          localsConvention: "camelCaseOnly", // 类名转为驼峰式（如 .user-name → userName）
          scopeBehaviour: "local", // 默认局部作用域
        },
        postcss: {
          plugins: [
            {
              postcssPlugin: "internal:charset-removal",
              AtRule: {
                charset: (atRule) => {
                  if (atRule.name === "charset") {
                    atRule.remove();
                  }
                },
              },
            },
          ],
        },
      },
    };
  },
);
